# -*- coding: utf-8 -*-
__author__ = 'BuddyHolly'

import os
from pptx import Presentation


# =========================================================
# *** PPT图片替换 ***
#
# pptx_path：ppt路径
# pic_path：替换图片路径
# infos：图片信息
#
# pptx_path中的ppt直接替换图片，无返回值
# =========================================================

def replace_pic(pptx_path, pic_path, infos):
    prs = Presentation(pptx_path)

    # info_list: [slide_id, shape_id]
    for info in infos:
        # 读入Slide与shape
        slide = prs.slides[info[0]]
        img = slide.shapes[info[1]]

        # ===============================================
        # 从当前shape中获取图片信息
        # pptx自建类shape中替换保护信息_blob（图像流信息）！！！
        # ===============================================
        # 从shape中获取当前info的图片信息
        img_pic = img._pic
        img_rid = img_pic.xpath('./p:blipFill/a:blip/@r:embed')[0]
        img_part = slide.part.related_parts[img_rid]

        # 打开替换图片
        filename = str(info[0]) + '_' + str(info[1]) + '.png'
        REPLACEMENT_IMG = os.path.join(pic_path, filename)
        with open(REPLACEMENT_IMG, 'rb') as f:
            rImgBlob = f.read()

        # 替换图片
        img_part._blob = rImgBlob

    # 原ppt直接替换后保存
    prs.save(pptx_path)
